﻿using System;
using System.Data;
using System.IO;
using System.Web.UI;
using Web.SystemLogin.Models;
using Web.SystemLogin.Services;

using Web.SystemConfig.Services;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using Web.SystemLogin.Business;
using DreamBuilder.Core.DAO;
using DreamBuilder.Core;
using DreamBuilder.Common;
using DreamBuilder.Core.Message;
using DreamBuilder.UI.UserControls;
using CommonModule;
using EPlanet.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.Practices.Unity;
using System.Web.UI.WebControls;
using DreamBuilder.UI.UserControls.UserControls;
using Web.Views.Public;
using System.Web;
using System.Runtime.InteropServices;

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}

namespace Web
{
    public enum PageState
    {
        /// <summary>
        /// 新增状态
        /// </summary>
        State_New = 1,

        /// <summary>
        /// 编辑状态
        /// </summary>
        State_Edit = 2,
    }

    public class PageCommonMethod
    {
        public static bool PopConfirm(Page page, HiddenField hidfield, string msg)
        {
            bool result = false;
            string a = @"<script type=""text/javascript"">
                var isConfirm =  confirm('" + msg +
                "'); document.getElementById('"
                + hidfield.ClientID +
                "').value = isConfirm</script>";
            page.ClientScript.RegisterStartupScript(page.GetType(), null, a);
            if (hidfield.Value.ToLower().Equals("true"))
            {
                result = true;
            }
            return result;
        }
    }

    /// <summary>
    /// 转换工具类
    /// </summary>
    public static class ConvertFormat
    {
        /// <summary>
        /// 转换时间为日期格式yyyy-MM-dd
        /// </summary>
        /// <param name="dt">DateTime对象</param>
        /// <returns></returns>
        public static string FormatToDate(this DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd");
        }
    }

    /// <summary>
    /// ToolBar的按钮形式
    /// </summary>
    public enum ToolMenuType
    {
        /// <summary>
        /// 浏览界面类型
        /// </summary>
        TYPE_MainList = 1,
        /// <summary>
        /// 编辑界面类型
        /// </summary>
        TYPE_Edit = 2,
        /// <summary>
        /// 报表界面类型
        /// </summary>
        TYPE_Report = 3,
        /// <summary>
        /// 查询界面类型
        /// </summary>
        TYPE_Search = 4
    }

    /// <summary>
    /// 列表查看权限类型
    /// </summary>
    public enum ViewType
    {
        /// <summary>
        /// 浏览全部记录
        /// </summary>
        ViewAll = 1,
        /// <summary>
        /// 浏览本部门员工以及下属部门员工创建的记录
        /// </summary>
        ViewDeptAll = 2,
        /// <summary>
        /// 浏览本部门员工创建的记录
        /// </summary>
        ViewDept = 3,
        /// <summary>
        /// 浏览本人创建的记录
        /// </summary>
        ViewCreate = 4,
        /// <summary>
        /// 没有浏览记录的权限
        /// </summary>
        ViewNone = 5
    }

    public class PageBase : EPPage
    {
        [Dependency]
        public ISystemLogin SystemLoginComponent
        {
            get;
            set;
        }
        //当前页面
        private string pageName;


        public string PageName
        {
            set
            {
                base.ID = value;
                pageName = value;
            }
            get
            {
                return pageName;
            }
        }

        /// <summary>
        /// 当前页面的菜单ID
        /// </summary>
        public string MenuID
        {
            get;
            set;
        }

        /// <summary>
        /// 编辑页面使用主表主键
        /// </summary>
        public string PKValue
        {
            get
            {
                return ((ViewState["PKValue"] == null) ? "" : ViewState["PKValue"].ToString());
            }
            set
            {
                ViewState["PKValue"] = value;
            }

        }


        public PageState CurrentPageState
        {
            get
            {
                return ((ViewState["CurrentPageState"] == null) ? PageState.State_New : (PageState)ViewState["CurrentPageState"]);
            }
            set
            {
                ViewState["CurrentPageState"] = value;
            }

        }

        /// <summary>
        /// Current Login user
        /// </summary>
        /// <remarks>
        /// 如果ModuleID为SystemLogin，则返回Session["CurrentUser"]
        /// 如果用户已经登录，并且Session["CurrentUser"]为空，则生成TopisUser实例并存储到Session["CurrentUser"]中并返回该值。
        /// 否则返回Session["CurrentUser"]
        /// 如果用户未登录，则返回null
        /// </remarks>
        public Web.SystemLogin.Models.User CurrentUser
        {

            get
            {
                if (PageName.ToLower() == "SystemLogin.SystemLogin".ToLower())
                {
                    return (Web.SystemLogin.Models.User)Session["CurrentUser"];
                }
                else
                {
                    if (Session["CurrentUser"] == null)
                    {
                        //更新用户的登录时间
                        //SystemLoginComponent.UpdateUserLoginInfo("guest");
                        //#region 记录登录日志
                        //OnlineUser ou = new OnlineUser();
                        //ILogger log = UContainer.Resolve<ILogger>(Category.LoginLog);
                        //log.Info(ou.GetLogInfo("guest", Request.UserHostAddress, Request.Browser.Platform, Thread.CurrentThread.CurrentUICulture.Name, Request.Browser.Type));
                        //#endregion
                        //FormsAuthentication.SetAuthCookie("guest", false);
                        //ISystemLogin systemlogin = UContainer.Resolve<ISystemLogin>();
                        //Web.SystemLogin.Models.User user = new Web.SystemLogin.Models.User();
                        //user.Login_ID = "guest";
                        //user.User_ID = "guest";
                        //Session["CurrentUser"] = user;// systemlogin.GetCurrentUser("guest");
                        //FormsAuthentication.SetAuthCookie("guest", false);
                        return null;
                    }
                    else
                    {
                        return (Web.SystemLogin.Models.User)Session["CurrentUser"];
                    }
                }
                //only after the user login
                //if (Page.User.Identity != null && Page.User.Identity.IsAuthenticated)
                //{
                //    if (Session["CurrentUser"] == null)
                //    {
                //        ISystemLogin systemlogin = UContainer.Resolve<ISystemLogin>();
                //        Session["CurrentUser"] = systemlogin.GetCurrentUser(Page.User.Identity.Name);
                //    }
                //    return (Web.SystemLogin.Models.User)Session["CurrentUser"];
                //}
                //else
                //{
                //    return null;
                //}
            }

        }

        private MasterPage masterPage;

        public MasterPage MasterPage
        {
            get
            {
                if (masterPage == null)
                {
                    masterPage = this.Master as Web.MasterPage;
                }
                return masterPage;
            }
        }

        /// <summary>
        /// 当前用户在当前页面的查看权限类型
        /// </summary>
        public ViewType CurrentViewType
        {
            get
            {
                if (ViewState["CurrentViewType"] == null)
                {
                    ViewState["CurrentViewType"] = this.GetViewType();
                }
                return (ViewType)ViewState["CurrentViewType"];
            }
            set
            {
                ViewState["CurrentViewType"] = value;
            }

        }

        protected virtual TREsult ExpHelper<TEntity, TREsult>(Func<TEntity, TREsult> func)
        {
            var item = this.GetDataItem();
            return func((TEntity)item);
        }

        #region 主题  add by guoyin 2011-07-22
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            this.Theme = "MSN_Blue";
        }
        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            this.DBHelpName = DBHelperString.Business;
            PageName = Request.CurrentExecutionFilePath.Remove(0, Request.ApplicationPath.Length + 1).Replace(".aspx", "");
            string PageDomain = PageName.Replace("/", ".");
            #region Session过期 add by guoyin 2012-02-21
            if (!(PageDomain.ToLower().Contains("Views.SystemLogin".ToLower()) || PageDomain.ToLower().Contains("Views.TempUserManage.TempUserLogin".ToLower())))
            {
                if (Session["CurrentUser"] == null)
                {
                    this.Page.Response.Redirect(Request.ApplicationPath + "/Views/SystemLogin/SystemLogin.aspx?ReturnUrl=" + this.Request.Url.AbsoluteUri + "");
                }
            }
            #endregion
            base.OnInit(e);
            this.Response.AddHeader("X-UA-Compatible", "IE=EmulateIE7");
        }

        /// <summary>
        /// 浏览单条数据
        /// </summary>
        /// <param name="sVoucherID">单据编号</param>
        /// <param name="sPKValue">单据数据主键</param>
        protected void ShowViewInfo(string sVoucherID, string sPKValue)
        {
            //string showViewScript = "<script>window.open(\"" + Request.ApplicationPath + "/UserControls/View.aspx?VoucherID=" + sVoucherID + "&DBHelperString=" + this.DBHelpName + "&PKValue=" + Server.UrlEncode(sPKValue) + "\",\"\",\"height=480, width=800, top=120, left=100, toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, status=no\"" + ")</script>";
            string showViewScript = "<script>window.showModelessDialog(\"" + Request.ApplicationPath + "/UserControls/View.aspx?VoucherID=" + sVoucherID + "&DBHelperString=" + this.DBHelpName + "&PKValue=" + Server.UrlEncode(sPKValue) + "\",\"\",\"dialogHeight=480px; dialogwidth=800px;dialogTop=120px;dialogLeft=100px;toolbar=no; scrollbars=yes; resizable=yes; status=no;\"" + ")</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "showView", showViewScript);
        }

        /// <summary>
        /// 显示帮助文件
        /// </summary>
        protected void ShowHelp()
        {
            string sHelpPath = "";

            while (PageName.IndexOf(".") > 0)
            {
                sHelpPath = sHelpPath + PageName.Substring(0, PageName.IndexOf(".")) + "/";
                PageName = PageName.Substring(PageName.IndexOf(".") + 1);
            }
            string showHelpScript = "<script>window.open(\"" + Request.ApplicationPath + "/help/" + sHelpPath + "Help.htm" + "\",\"\",\"height=500, width=800, top=120, left=100, toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, status=no\"" + ")</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "showHelp", showHelpScript);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataSet"></param>
        /// <param name="page"></param>
        protected void ExportListToExcel(System.Data.DataSet dataSet, System.Web.UI.Page page)
        {
            ExcelHelper excel = new ExcelHelper();
            excel.CreateExcel(dataSet, page);
        }

        /// <summary>
        /// 获取工具条配置文件路径
        /// </summary>
        /// <returns></returns>
        public string GetToolMenuPath(ToolMenuType nToolMenuType)
        {
            try
            {
                string sFilePath = "";

                if (PageName != null)
                {
                    string sPageName = PageName;
                    //获取页面名已经去除后缀名
                    //sPageName = sPageName.Substring(0, sPageName.LastIndexOf("."));
                    //页面需要特殊的工具条配置
                    if (nToolMenuType == ToolMenuType.TYPE_MainList)
                    {
                        sFilePath = Server.MapPath(Request.ApplicationPath + "/" + sPageName.Replace(".", "/") + "/" + PageName + ".MainToolBarInfo.xml");
                    }
                    else if (nToolMenuType == ToolMenuType.TYPE_Edit)
                    {
                        sFilePath = Server.MapPath(Request.ApplicationPath + "/" + sPageName.Replace(".", "/") + "/" + PageName + ".EditToolBarInfo.xml");
                    }
                    else if (nToolMenuType == ToolMenuType.TYPE_Report)
                    {
                        sFilePath = Server.MapPath(Request.ApplicationPath + "/" + sPageName.Replace(".", "/") + "/" + PageName + ".ReportToolBarInfo.xml");
                    }
                    else if (nToolMenuType == ToolMenuType.TYPE_Search)
                    {
                        sFilePath = Server.MapPath(Request.ApplicationPath + "/" + sPageName.Replace(".", "/") + "/" + PageName + ".SearchToolBarInfo.xml");
                    }
                    //使用公共的工具条配置
                    if (System.IO.File.Exists(sFilePath) == false)
                    {
                        if (nToolMenuType == ToolMenuType.TYPE_MainList)
                        {
                            sFilePath = Server.MapPath(Request.ApplicationPath + "/Config/MainToolBarInfo.xml");
                        }
                        else if (nToolMenuType == ToolMenuType.TYPE_Edit)
                        {
                            sFilePath = Server.MapPath(Request.ApplicationPath + "/Config/EditToolBarInfo.xml");
                        }
                        else if (nToolMenuType == ToolMenuType.TYPE_Report)
                        {
                            sFilePath = Server.MapPath(Request.ApplicationPath + "/Config/ReportToolBarInfo.xml");
                        }
                        else if (nToolMenuType == ToolMenuType.TYPE_Search)
                        {
                            sFilePath = Server.MapPath(Request.ApplicationPath + "/Config/SearchToolBarInfo.xml");
                        }
                    }
                    return sFilePath;
                }
                else
                {
                    return "";
                }
            }
            catch (System.Exception err)
            {
                return "";
            }
        }


        /// <summary>
        /// 创建工具栏的按钮
        /// </summary>
        /// <param name="pToolBar">指定的工具栏</param>
        protected void CreateToolMenu(EPlanet.Web.UI.WebControls.ToolBar pToolBar, ToolMenuType nToolMenuType)
        {
            try
            {
                if (pToolBar != null)
                {
                    pToolBar.EnableViewState = false;
                    pToolBar.DataSource = GetToolMenuPath(nToolMenuType);
                    pToolBar.ImagePath = System.Web.HttpContext.Current.Request.ApplicationPath + "/Images/Office2003/";
                    /*ADD  BY guoyin  添加工具条的样式*/
                    //pToolBar.Style.Add(HtmlTextWriterStyle.Position, "fixed");
                    //pToolBar.Style.Add(HtmlTextWriterStyle.ZIndex, "200");
                    //pToolBar.BackColor =System.Drawing.ColorTranslator.FromHtml("#f8f8f8");
                    pToolBar.DataBind();
                    foreach (EPlanet.Web.UI.WebControls.MenuItem menuItem in pToolBar.Items)
                    {
                        //add by 崔茂山 删除按钮添加提示
                        if (menuItem.ID == "tbDelete")
                        {

                            getAllCtl(Page.Controls, menuItem, pToolBar);

                        }
                        if (menuItem.ID == "tbHelp")
                        {
                            string scripts = "javascript:window.open(\"" + Request.ApplicationPath + "/HelpDocs/常见问题.mht\",\"\",\"height=580, width=700, top=120, left=100, toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, status=no\"" + ");";
                            menuItem.Url = "" + scripts + "" + this.Page.GetPostBackClientEvent(pToolBar, menuItem.ID);
                        }
                        menuItem.Label = CResManager.GetPublicString("ToolMenuItem", menuItem.ID);
                    }
                }
            }
            catch (System.Exception err)
            { }
        }
        private void getAllCtl(ControlCollection ctls, EPlanet.Web.UI.WebControls.MenuItem menuItem, ToolBar pToolBar)
        {
            foreach (Control c in ctls)
            {
                if (c is UCList)
                {
                    UCList list = (UCList)c;
                    menuItem.Url = " javascript:if(toolBarMultyDelete('" + list.ClientID + "','" + GetPublicString("string", "alertNullPkValue") + "','" + GetPublicString("ToolMenuItem", "AllDeleteConfirm") + "')) " + this.Page.GetPostBackClientEvent(pToolBar, menuItem.ID);
                }
                if (c.HasControls())
                {
                    getAllCtl(c.Controls, menuItem, pToolBar);
                }
            }
        }

        /// <summary>
        /// function to get the string of the current culture
        /// </summary>
        /// <param name="name">the string name</param>
        /// <returns>the localized string </returns>
        /// <remarks>
        /// 通过MyResouceManager获取此模块对应的资源文件中制定字符串
        /// </remarks>
        public string GetString(string name)
        {
            return CResManager.GetString(PageName, name);
        }

        /// <summary>
        /// function to get the public string of the current culture
        /// </summary>
        /// <param name="resBaseName">the res Base name</param>
        /// <param name="name">the string name</param>
        /// <returns>the localized string </returns>
        /// <remarks>
        /// 通过MyResouceManager获取此模块对应的资源文件中制定字符串
        /// </remarks>
        public string GetPublicString(string resBaseName, string name)
        {
            return CResManager.GetPublicString(resBaseName, name);
        }

        /// <summary>
        /// 在状态栏显示信息
        /// </summary>
        /// <param name="message"></param>
        public void DisplayMessage(string message)
        {
            string errorMsg = this.GetString(message);
            string publicErrorMsg = this.GetPublicString("FrameError", message);

            if (!string.IsNullOrEmpty(errorMsg))
            {
                this.MasterPage.StatusMessage += errorMsg;
            }
            else if (!string.IsNullOrEmpty(publicErrorMsg))
            {
                this.MasterPage.StatusMessage += publicErrorMsg;
            }
            else
            {
                this.MasterPage.StatusMessage += message;
            }
        }

        protected override void SavePageStateToPersistenceMedium(object state)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter writer = new StringWriter();
            formatter.Serialize(writer, state);
            string viewState = writer.ToString();
            byte[] data = Convert.FromBase64String(viewState);
            byte[] compressedData = ViewStateManager.Compress(data);
            string str = Convert.ToBase64String(compressedData);
            ClientScript.RegisterHiddenField("__EPVIEWSTATE", str);
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            string viewstate = Request.Form["__EPVIEWSTATE"];
            byte[] data = Convert.FromBase64String(viewstate);
            byte[] uncompressedData =
            ViewStateManager.Decompress(data);
            string str = Convert.ToBase64String(uncompressedData);
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(str);
        }

        protected void Alert(string message)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>$(function(){alert('" + message + "')});</script>");
            //ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('" + message + "');</script>");
        }

        protected void MyAlert(string msg, string url)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert(\"" + msg + "\");window.location.href=\"" + url + "\"</script>");
        }

        #region add by guoyin   记录日志 && OCS集成
        /// <summary>
        /// 异常日志记录方法(默认类别为系统日志)
        /// </summary>
        /// <param name="message"></param>
        protected void WriteErrorLog(string message)
        {
            ILogger log = UContainer.Resolve<ILogger>(Category.SMErrorLog);
            OnlineUser ou = new OnlineUser();
            //系统配置异常日志编号
            string smallCategory = ((int)OracleLogType.System).ToString();
            string operationMessage = message;
            string strLog = smallCategory + "@@@" + operationMessage;
            log.Info(strLog);
        }
        /// <summary>
        /// 异常日志记录方法 加小类
        /// </summary>
        /// <param name="message"></param>
        /// <param name="smallcategory"></param>
        protected void WriteErrorLog(string message, OracleLogType logtype )
        {
            ILogger log = UContainer.Resolve<ILogger>(Category.SMErrorLog);
            OnlineUser ou = new OnlineUser();
            //系统配置异常日志编号
            string smallCategory = ((int)logtype).ToString();
            string operationMessage = message;
            string strLog = smallCategory + "@@@" + operationMessage;
            log.Info(strLog);
        }
        /// <summary>
        /// 用户日志记录方法
        /// </summary>
        /// <param name="message"></param>
        /// <param name="smallcategory"></param>
        public void WriteUserLog(string message, OracleLogType logtype)
        {
            ILogger log = UContainer.Resolve<ILogger>(Category.SMInfoLog);
            OnlineUser ou = new OnlineUser();
            //操作日志小类编号
            string smallCategory = ((int)logtype).ToString();
            string operationMessage = message;
            // this.CurrentUser.
            string strLognomal =   smallCategory + "@@@" + this.CurrentUser.All_Org_Name + this.CurrentUser.User_Name + "[ " + this.CurrentUser.User_ID + " ]," + operationMessage;
            string strLogAuthority = smallCategory+"@@@" + this.CurrentUser.All_Org_Name + this.CurrentUser.User_Name + "[ " + this.CurrentUser.User_ID + " ]" + "授权" + this.CurrentUser.Real_Name + "[ " + this.CurrentUser.Real_ID + " ]," + operationMessage;
            string strLog = strLognomal;
            if (this.CurrentUser.User_ID != this.CurrentUser.Real_ID)
            {
                strLog = strLogAuthority;
            }
            log.Info(strLog);
        }
        ///// <summary>
        ///// 返回集成OCS信息
        ///// </summary>
        /////<param name="UserId">需要绑定人的UserID</param>
        ///// <returns></returns>
        //protected string WFGetOcsString(string UserId)
        //{
        //    IAuth_User IUser = UContainer.Resolve<IAuth_User>();
        //    DataTable userInfo = IUser.GetUserInfo(UserId);
        //    string email = "";
        //    string username = "";
        //    if (userInfo.Rows.Count > 0)
        //    {
        //        email = userInfo.Rows[0]["Login_Id"].ToString(); //用LoginId绑
        //        username = userInfo.Rows[0]["User_Name"].ToString();
        //    }
        //    string ocsName = email;
        //    if (email.IndexOf("@") > 0)  //判断邮箱的@符号
        //    {
        //        //ocsName = email.Remove(0, email.IndexOf("\\") + 1);
        //        ocsName = email.Remove(email.IndexOf("@"));
        //    }
        //    string rString = @"<table align='center'><tr><td align='center'><img id=" + CreateImnid(username) + " title=\"\" border=\"0\" name=\"imnmark\" alt=\"无联机状态信息\" src=\"../../../Images/OcsState/imnUnknown.png\" ShowOfflinePawn=\"true\" haveSubscribed=\"false\" style=\"width:16px; height:16px\" valign=\"middle\" sip=\"sip:" + ocsName + "@bgpuc.com.cn\">" + username + "</td></tr></table>";
        //    return rString;
        //}
        ///// <summary>
        ///// 返回集成OCS信息
        ///// </summary>
        /////<param name="UserId">需要绑定人的UserID</param>
        ///// <returns></returns>
        //protected string GetOcsString(string UserId)
        //{
        //    IAuth_User IUser = UContainer.Resolve<IAuth_User>();
        //    DataTable userInfo = IUser.GetUserInfo(UserId);
        //    string email = "";
        //    string username = "";
        //    if (userInfo.Rows.Count > 0)
        //    {
        //        email = userInfo.Rows[0]["Login_Id"].ToString(); //用LoginId绑
        //        username = userInfo.Rows[0]["User_Name"].ToString();
        //    }
        //    string ocsName = email;
        //    if (email.IndexOf("@") > 0)  //判断邮箱的@符号
        //    {
        //        //ocsName = email.Remove(0, email.IndexOf("\\") + 1);
        //        ocsName = email.Remove(email.IndexOf("@"));
        //    }
        //    string rString = @"<table align='center'><tr><td align='center'><img id=" + CreateImnid(username) + " title=\"\" border=\"0\" name=\"imnmark\" alt=\"无联机状态信息\" src=\"../../Images/OcsState/imnUnknown.png\" ShowOfflinePawn=\"true\" haveSubscribed=\"false\" style=\"width:16px; height:16px\" valign=\"middle\" sip=\"sip:" + ocsName + "@bgpuc.com.cn\">" + username + "</td></tr></table>";
        //    return rString;
        //}

        /// <summary>
        /// OCS创建图标id
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        int inum = 0;
        protected string CreateImnid(string sid)
        {
            return string.Format("imn{0}{1},type=sip", sid, inum++);
        }
        #endregion
        #region 权限管理

        /// <summary>
        /// 获取当前用户在当前页面的浏览类型
        /// </summary>
        /// <returns></returns>
        protected ViewType GetViewType()
        {
            ViewType viewType;

            #region 判断处理是否有全部查看权限
            if (!HasAuthority("ViewAll"))
            {
                #region 判断处理是否有本部门以及下属部门的查看权限
                if (!HasAuthority("ViewDeptAll"))
                {
                    #region 判断处理是否有本部门查看权限
                    if (!HasAuthority("ViewDept"))
                    {
                        #region 判断处理是否有个人查看权限
                        if (!HasAuthority("ViewCreate"))
                        {
                            viewType = ViewType.ViewNone;
                        }
                        else
                        {
                            viewType = ViewType.ViewCreate;
                        }
                        #endregion
                    }
                    else
                    {
                        viewType = ViewType.ViewDept;
                    }
                    #endregion
                }
                else
                {
                    viewType = ViewType.ViewDeptAll;
                }
                #endregion
            }
            else
            {
                viewType = ViewType.ViewAll;
            }
            #endregion
            return viewType;
        }

        /// <summary>
        /// 没有查看权限，跳转到无查看权限的错误提示页面
        /// </summary>
        protected void ViewNoneShow()
        {
            Session[MessageInfo.MsgKey] = MessageHandler.CreateMessageByMessage("NoViewFunc");
            this.Response.Redirect("~/ErrorPage.aspx");
        }

        /// <summary>
        /// 加个人查看的条件
        /// </summary>
        protected string ViewCreateSql()
        {
            IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();
            string CreateByField = BusUserRoleFunction.GetCreateByField(this.MenuID);
            //检查当前节点是否配置了创建人的字段
            CheckCreateByFieldName(CreateByField);
            //加个人查看的条件
            string filterSql = GetCreateByString(CreateByField);
            return filterSql;
        }

        /// <summary>
        /// 本部门查看权限条件
        /// </summary>
        protected string ViewDeptSql()
        {
            IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();
            string CreateByField = BusUserRoleFunction.GetCreateByField(this.MenuID);
            //检查当前节点是否配置了创建人的字段
            CheckCreateByFieldName(CreateByField);

            //加部门过滤的条件
            //两种情况，如果当前人没有部门，则只能看到自己所创建的条数
            //如果有部门，则直接加部门的过滤条件就行了
            string filterSql = string.Empty;
            if (string.IsNullOrEmpty(this.CurrentUser.ORG_ID))
            {
                //当前登录人无部门，则只能看到他本人创建的记录
                filterSql = GetCreateByString(CreateByField);
            }
            else
            {
                //有部门，则通过部门过滤
                filterSql = GetDeptString(CreateByField);
            }
            return filterSql;
        }


        /// <summary>
        /// 本部门以及下属部门查看权限
        /// </summary>
        protected string ViewDeptAllSql()
        {
            IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();
            string CreateByField = BusUserRoleFunction.GetCreateByField(this.MenuID);
            //检查当前节点是否配置了创建人的字段
            CheckCreateByFieldName(CreateByField);

            //加部门过滤的条件
            //两种情况，如果当前人没有部门，则只能看到自己所创建的条数
            //如果有部门，则添加本部门以及下属部门的过滤条件
            string filterSql = string.Empty;
            if (string.IsNullOrEmpty(this.CurrentUser.ORG_ID))
            {
                //当前登录人无部门，则只能看到他本人创建的记录
                filterSql = GetCreateByString(CreateByField);
            }
            else
            {
                //有部门，则通过部门过滤
                filterSql = GetDeptAllString(CreateByField);
            }
            return filterSql;
        }



        /// <summary>
        /// 列表页面权限控制
        /// </summary>
        /// <param name="Toolbar1"></param>
        /// <param name="uclistRemark"></param>
        protected void CheckListAuthorities(EPlanet.Web.UI.WebControls.ToolBar Toolbar1, UCList ucList)
        {
            IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();

            //string CreateByField = BusUserRoleFunction.GetCreateByField(this.MenuID);

            //#region 判断处理是否有全部查看权限

            //if (!HasAuthority("ViewAll"))
            //{
            //    #region 判断处理是否有本部门以及下属部门的查看权限
            //    if (!HasAuthority("ViewDeptAll"))
            //    {
            //        #region 判断处理是否有本部门查看权限
            //        if (!HasAuthority("ViewDept"))
            //        {
            //            #region 判断处理是否有个人查看权限
            //            if (!HasAuthority("ViewCreate"))
            //            {
            //                //没有查看权限，跳转到无查看权限的错误提示页面
            //                Session[MessageInfo.MsgKey] = MessageHandler.CreateMessageByMessage("NoViewFunc");
            //                this.Response.Redirect("~/ErrorPage.aspx");
            //            }
            //            else
            //            {
            //                #region 添加个人查看权限条件
            //                //检查当前节点是否配置了创建人的字段
            //                CheckCreateByFieldName(CreateByField);
            //                //加个人查看的条件
            //                string filterSql = GetCreateByString(CreateByField);
            //                AddUCListFilter(ucList, filterSql);
            //                #endregion
            //            }
            //            #endregion
            //        }
            //        else
            //        {

            //            #region 添加本部门查看权限条件
            //            //检查当前节点是否配置了创建人的字段
            //            CheckCreateByFieldName(CreateByField);

            //            //加部门过滤的条件
            //            //两种情况，如果当前人没有部门，则只能看到自己所创建的条数
            //            //如果有部门，则直接加部门的过滤条件就行了
            //            string filterSql = string.Empty;
            //            if (string.IsNullOrEmpty(this.CurrentUser.ORG_ID))
            //            {
            //                //当前登录人无部门，则只能看到他本人创建的记录
            //                filterSql = GetCreateByString(CreateByField);
            //            }
            //            else
            //            {
            //                //有部门，则通过部门过滤
            //                filterSql = GetDeptString(CreateByField);
            //            }

            //            AddUCListFilter(ucList, filterSql);
            //            #endregion
            //        }
            //        #endregion
            //    }
            //    else
            //    {
            //        #region 添加本部门以及下属部门查看权限
            //        //检查当前节点是否配置了创建人的字段
            //        CheckCreateByFieldName(CreateByField);

            //        //加部门过滤的条件
            //        //两种情况，如果当前人没有部门，则只能看到自己所创建的条数
            //        //如果有部门，则添加本部门以及下属部门的过滤条件
            //        string filterSql = string.Empty;
            //        if (string.IsNullOrEmpty(this.CurrentUser.ORG_ID))
            //        {
            //            //当前登录人无部门，则只能看到他本人创建的记录
            //            filterSql = GetCreateByString(CreateByField);
            //        }
            //        else
            //        {
            //            //有部门，则通过部门过滤
            //            filterSql = GetDeptAllString(CreateByField);
            //        }

            //        AddUCListFilter(ucList, filterSql);
            //        #endregion
            //    }
            //    #endregion
            //}
            //else
            //{
            //    //有查看全部的条件，目前不用加过滤条件
            //}
            //#endregion


            if (CurrentViewType == ViewType.ViewNone)
            {
                ViewNoneShow();
            }

            if (!HasAuthority("Add"))
            {
                ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Add, false);
            }
            if (!HasAuthority("Update"))
            {
                ucList.ShowEditCommand = false;
            }

            if (!HasAuthority("Delete"))
            {
                ucList.ShowDeleteCommand = false;
                ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Delete, false);
            }

            if (!HasAuthority("ViewFilterColumm"))
            {
                string encryptColumnFields = BusUserRoleFunction.GetEncryptColumnFields(this.MenuID);
                ucList.EncryptColumnFields = encryptColumnFields;
            }
        }

        /// <summary>
        /// 列表页面权限控制
        /// </summary>
        /// <param name="Toolbar1"></param>
        /// <param name="uclistRemark"></param>
        protected void CheckListAuthorities(EPlanet.Web.UI.WebControls.ToolBar Toolbar1, DreamBuilder.UI.UserControls.SPageList ucList)
        {
            IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();

            if (CurrentViewType == ViewType.ViewNone)
            {
                ViewNoneShow();
            }

            if (!HasAuthority("Add"))
            {
                ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Add, false);
            }
            if (!HasAuthority("Update"))
            {
                ucList.ShowEditCommand = false;
            }

            if (!HasAuthority("Delete"))
            {
                ucList.ShowDeleteCommand = false;
                ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Delete, false);
            }

            if (!HasAuthority("ViewFilterColumm"))
            {
                string encryptColumnFields = BusUserRoleFunction.GetEncryptColumnFields(this.MenuID);
                ucList.EncryptColumnFields = encryptColumnFields;
            }
        }

        /// <summary>
        /// 编辑页面权限控制
        /// </summary>
        /// <param name="Toolbar1"></param>
        /// <param name="uclistRemark"></param>
        protected void CheckEditAuthorities(PageState pageState)
        {
            if (pageState == PageState.State_New)
            {
                if (!HasAuthority("Add"))
                {
                    //没有编辑权限，跳转到无编辑权限的错误提示页面
                    Session[MessageInfo.MsgKey] = MessageHandler.CreateMessageByMessage("NoAddFunc");
                    this.Response.Redirect("~/ErrorPage.aspx");
                }
            }
            else
            {
                if (!HasAuthority("Update"))
                {
                    //没有编辑权限，跳转到无编辑权限的错误提示页面
                    Session[MessageInfo.MsgKey] = MessageHandler.CreateMessageByMessage("NoUpdateFunc");
                    this.Response.Redirect("~/ErrorPage.aspx");
                }
            }
        }


        /// <summary>
        /// 个人查看权限过滤语句
        /// </summary>
        /// <returns></returns>
        virtual protected string GetCreateByString(string CreateByField)
        {
            string filterSql = " (" + CreateByField + " = '" + CurrentUser.User_ID + "') ";
            return filterSql;
        }

        /// <summary>
        /// 部门查看权限过滤语句
        /// </summary>
        /// <param name="CreateByField"></param>
        /// <returns></returns>
        private string GetDeptString(string CreateByField)
        {
            string filterSql = " (" + CreateByField + @" in 
                                                ( SELECT distinct User_ID from P_Auth_User 
                                                    where ORG_ID in 
                                                        (select ORG_ID from P_Auth_User where User_ID ='" + CurrentUser.User_ID + @"' ) 
                                                ) ) ";
            return filterSql;
        }

        private string GetDeptAllString(string CreateByField)
        {
            string filterSql = " (" + CreateByField + @" in 
                                                ( SELECT distinct User_ID from P_Auth_User 
                                                    where ORG_ID in 
                                                        (select distinct OrgID from f_GetUserAllOrgIDWithChild('" + CurrentUser.User_ID + @"') ) 
                                                ) ) ";
            return filterSql;
        }

        /// <summary>
        /// 添加过滤语句，在已加的过滤条件上附加权限控制的语句
        /// </summary>
        /// <param name="ucList"></param>
        /// <param name="filterSql"></param>
        virtual protected void AddUCListFilter(UCList ucList, string filterSql)
        {
            if (string.IsNullOrEmpty(ucList.FilterSqlWhere))
            {
                //如果原来没有加过滤条件，则直接加上过滤条件
                ucList.FilterSqlWhere = filterSql;
            }
            else
            {
                //如果原来有过滤条件，则先加上原来的过滤条件，在加权限控制的条件
                ucList.FilterSqlWhere = " ( " + ucList.FilterSqlWhere + " ) and " + filterSql;
            }
        }


        /// <summary>
        /// 检查当前节点是否配置了创建人的字段
        /// </summary>
        /// <param name="CreateByField"></param>
        private void CheckCreateByFieldName(string CreateByField)
        {
            if (string.IsNullOrEmpty(CreateByField))
            {
                //模块没有配置创建人的列名
                throw new Exception("模块没有配置创建人的列名!");
            }
        }

        /// <summary>
        /// function to test whether current user has the authority
        /// </summary>
        /// <param name="authorityType"></param>
        /// <returns></returns>
        /// <remarks>
        /// 为了提供系统性能，不是每次都访问数据库来判断用户权限。
        /// 下面两种情况将需要从数据库中获取当前用户具有的所有权限：
        /// (1)用户登录。
        /// (2)Session失效。
        /// 此函数从Session中存储的用户权限数据表中查找是否含有此模块＋权限类型的权限，如果有则返回true，否则返回false
        /// </remarks>
        protected bool HasAuthority(string authorityType)
        {
            return HasAuthority(authorityType, MenuID);
        }


        protected bool HasAuthority(string authorityType, string MenuID)
        {
            if (CurrentUser == null)
            {
                return false;
            }
            DataTable tblauth = null;
            string OALoginUserID = Session["OALoginUserID"].ToString();
            if (OALoginUserID != CurrentUser.User_ID)
            {
                Session["AllAuthoritiesOfUser"] = null;
            }
            if (Session["AllAuthoritiesOfUser"] == null)
            {
                IUserRoleFunction BusUserRoleFunction = UContainer.Resolve<IUserRoleFunction>();
                tblauth = BusUserRoleFunction.SelectFunctionsTableByUserID(CurrentUser.User_ID);
                tblauth.PrimaryKey = new DataColumn[] { tblauth.Columns["Func_Code"] };
                Session["AllAuthoritiesOfUser"] = tblauth;
                Session["OALoginUserID"] = CurrentUser.User_ID;
            }
            else
            {
                tblauth = (DataTable)Session["AllAuthoritiesOfUser"];
            }

            if (tblauth.Rows.Find(MenuID + "." + authorityType) != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
        /// <summary>
        /// 获取要删除的附件表
        /// </summary>
        /// <param name="objectTableCode"></param>
        /// <param name="objectID"></param>
        /// <returns></returns>
        protected DataTable GetAttachmentDeleteDataTable(string objectTableCode, string objectID)
        {
            IDBHelper dbHelper = DBHelperFactory.CreateInstance(DbHelperName.Dictionary);
            DataTable dtAttachments = null;
            string sSql = "select P_BT_Attachments.*,'3' as RowStatus from P_BT_Attachments where ObjectTableName = '" + objectTableCode + "' and ObjectID = '" + objectID + "'";
            dtAttachments = dbHelper.ExecuteDataSet(sSql).Tables[0];
            dtAttachments.PrimaryKey = new DataColumn[] { dtAttachments.Columns["AttachmentID"] };
            dtAttachments.TableName = "P_BT_Attachments";
            return dtAttachments.Copy();
        }



        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        /// <summary>
        /// 获取用户的Mac地址
        /// </summary>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        protected string GetUserMacSrc(out string errmsg)
        {
                // 在此处放置用户代码以初始化页面
                try
                {
                    errmsg = string.Empty;
                    string userip = Request.UserHostAddress;
                    string strClientIP = Request.UserHostAddress.ToString().Trim();
                    Int32 ldest = inet_addr(strClientIP); //目的地的ip 
                    Int32 lhost = inet_addr("");   //本地服务器的ip 
                    Int64 macinfo = new Int64();
                    Int32 len = 6;
                    int res = SendARP(ldest, 0, ref macinfo, ref len);
                    string mac_src = macinfo.ToString("X");
                    if (mac_src == "0")
                    {
                        return string.Empty;
                    }
                    while (mac_src.Length < 12)
                    {
                        mac_src = mac_src.Insert(0, "0");
                    }

                    string mac_dest = "";

                    for (int i = 0; i < 11; i++)
                    {
                        if (0 == (i % 2))
                        {
                            if (i == 10)
                            {
                                mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                            }
                            else
                            {
                                mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                            }
                        }
                    }

                    return mac_dest;
                }
                catch (Exception err)
                {
                    errmsg = err.Message;
                    return string.Empty;
                }
        }

        /// <summary>
        /// 程序中存在异常报出的信息
        /// </summary>
        protected void ExceptionMsg()
        {
            string strMsg = "存在相关数据，请联系管理员！";
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('" + strMsg + "');", true);
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="strMsg"></param>
        protected void ShowMsg(string strMsg)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('" + strMsg + "');", true);
        }

        /// <summary>
        /// 关闭当前窗口
        /// </summary>
        protected void CloseCurPage()
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('此流程您已经处理，系统帮您刷新页面！');", true);
        }

        /// <summary>
        /// 获取要删除的子表
        /// </summary>
        /// <param name="tableCode">子表表名</param>
        /// <param name="primaryField">子表主键</param>
        /// <param name="parentField">子表外键</param>
        /// <param name="parentFieldValue">子表外键值</param>
        /// <returns></returns>
        protected DataTable GetChildDeleteDataTable(string tableCode, string primaryField, string parentField, string parentFieldValue)
        {
            DataTable dt = null;
            string sSql = "select " + tableCode + ".*,'3' as RowStatus from " + tableCode + " where " + parentField + " = '" + parentFieldValue + "'";
            IDBHelper dbHelper = DBHelperFactory.CreateInstance(DbHelperName.Dictionary);
            dt = dbHelper.ExecuteDataSet(sSql).Tables[0];
            dt.PrimaryKey = new DataColumn[] { dt.Columns[primaryField] };
            dt.TableName = tableCode;
            return dt.Copy();
        }

        /// <summary>
        /// 给DataTable添加序号
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="colXuHao"></param>
        protected void dbDataTableAddXuHao(DataTable dt, string colXuHao)
        {
            dt.Columns.Add(colXuHao);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][colXuHao] = i + 1;
            }
        }

        #region 非框架页面增加工具条

        protected void CheckToolMenu(EPlanet.Web.UI.WebControls.ToolBar Toolbar1, string status)
        {
            switch (status)
            {
                case "0":
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Add, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Cancel, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Delete, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Export, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Save, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Help, true);
                    break;
                case "1":
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Add, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Cancel, true);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Delete, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Export, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Save, false);
                    ToolBarHelper.SetToolBarVisible(Toolbar1, ToolBarID.Help, true);
                    break;
                default:
                    break;

            }
        }

        #endregion

        /// <summary>
        /// 根据菜单链接获取菜单menuId
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetMenuIdByUrl(string url)
        {
            string sql = "select * from P_auth_Menu where menu_url='" + url + "'";
            IMDataHelper dal = new IMDataHelper();
            DataSet ds = dal.DBHelper.ExecuteDataSet(sql);
            string menuId = string.Empty;
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                menuId = ds.Tables[0].Rows[0]["menu_Id"].ToString();
            }
            return menuId;
        }

        /// <summary>
        /// 检查菜单权限.
        /// </summary>
        public bool CheckMenuRight(string url)
        {
            //string url = this.Request.AppRelativeCurrentExecutionFilePath.Remove(0, 2);
            string menuId = GetMenuIdByUrl(url);
            bool hasAuthority = false;
            if (!string.IsNullOrEmpty(menuId))
            {
                IMDataHelper dal = new IMDataHelper();
                string sqlstr = @"select count(f.Func_ID) from P_Auth_Function f join P_Auth_Role_Function r 
			on f.Func_ID=r.Func_ID
			join P_Auth_User_Role ur on ur.Role_ID=r.Role_ID
			where ur.User_ID='" + this.CurrentUser.User_ID + "' and f.Menu_ID='" + menuId + "'";
                int o = Convert.ToInt32(dal.DBHelper.ExecuteScalar(sqlstr));
                hasAuthority = o > 0 ? true : false;
            }
            return hasAuthority;
        }

        private string _op;
        /// <summary>
        /// 操作类型
        /// add新建 edit编辑
        /// </summary>
        protected string OP
        {
            get
            {
                if (string.IsNullOrEmpty(this._op))
                {
                    _op = Request.QueryString["op"];
                }
                return _op;
            }
            set
            {
                _op = value;
            }
        }

        /// <summary>
        /// 扩展的页面日期校验
        /// </summary>
        /// <param name="datetime">字符串类型日期</param>
        /// <param name="errmsg">输出参数，错误信息（校验正确则没有错误信息）</param>
        /// <returns></returns>
        protected bool VelidateDate(string datetime, out string errmsg)
        {
            DateTime o_time = DateTime.Now;
            errmsg = string.Empty;
            bool bReturn = true;
            //对于非空字段进行校验
            if (!string.IsNullOrEmpty(datetime) && !DateTime.TryParse(datetime, out o_time))
            {
                errmsg = "【" + datetime + "】:不是正确的时间格式!";
                bReturn = false;
            }
            return bReturn;
        }

        /// <summary>
        /// 扩展的页面数字校验(Decimale)
        /// </summary>
        /// <param name="number">字符串类型数字</param>
        /// <param name="errmsg">输出参数，错误信息（校验正确则没有错误信息）</param>
        /// <returns></returns>
        protected bool VelidateNumber(string number, out string errmsg)
        {
            decimal o_d = decimal.Zero;
            errmsg = string.Empty;
            bool bReturn = true;
            //对于非空字段进行校验
            if (!string.IsNullOrEmpty(number) && !decimal.TryParse(number, out o_d))
            {
                errmsg = "【" + number + "】:不是正确的数字格式!";
                bReturn = false;
            }
            return bReturn;
        }

        /// <summary>
        /// 扩展的页面整型数值校验(Int)
        /// </summary>
        /// <param name="integer">字符串类型数字</param>
        /// <param name="errmsg">输出参数，错误信息（校验正确则没有错误信息）</param>
        /// <returns></returns>
        protected bool VelidateInteger(string integer, out string errmsg)
        {
            int o_d = 0;
            errmsg = string.Empty;
            bool bReturn = true;
            //对于非空字段进行校验
            if (!string.IsNullOrEmpty(integer) && !int.TryParse(integer, out o_d))
            {
                errmsg = "【" + integer + "】:不是正确的整数格式!";
                bReturn = false;
            }
            return bReturn;
        }
    }
}
